# 批量更改properties的横竖屏显示
import logging
import os

from constants.constant import EXCEL_PATH
from model.AppInfo import AppInfo
from utils.FileUtil import processExcel, read_properties, save_config_to_properties


def changeOrientationToEN():
    try:
        appInfos = processExcel(EXCEL_PATH)
    except Exception:
        logging.error("读取config/appInfos.xlsx错误：请确保文件存在")
        raise
    for appInfo in appInfos:
        try:
            propertiesPath = os.getcwd() + "\\8月鸿蒙产品_第一批\\" + str(appInfo.order_id) +"\\config.properties"

            appInfoDict = read_properties(propertiesPath)
            newAppInfo = AppInfo()
            newAppInfo.app_name = appInfoDict["app_name"]
            newAppInfo.version_name = appInfoDict["version_name"]
            newAppInfo.version_code = appInfoDict["version_code"]
            newAppInfo.package_name = appInfoDict["package_name"]
            newAppInfo.app_id = appInfoDict["app_id"]
            newAppInfo.orientation = appInfoDict["orientation"]
            newAppInfo.ad_id_banner = appInfoDict["ad_id_banner"]
            newAppInfo.ad_id_reward = appInfoDict["ad_id_reward"]
            newAppInfo.ad_id_interstitial = appInfoDict["ad_id_interstitial"]
            newAppInfo.ad_id_splash_1 = appInfoDict["ad_id_splash_1"]
            newAppInfo.order_id = appInfo.order_id

            save_config_to_test_properties(newAppInfo)
        except Exception:
            print(appInfo.app_name+ "error")

def changeDirNameToOrderId():
    try:
        appInfos = processExcel(EXCEL_PATH)
    except Exception:
        logging.error("读取config/appInfo.xlsx错误：请确保文件存在")
        raise
    for appInfo in appInfos:
        oldDirName = os.getcwd() + "\\8月鸿蒙产品_第一批\\" + appInfo.app_name
        newDirName = os.getcwd() + "\\8月鸿蒙产品_第一批\\" + str(appInfo.order_id)

        os.rename(oldDirName, newDirName)

def getErrorDir():
    errNameCount = 0
    for dir in os.listdir(os.getcwd() + "\\8月鸿蒙产品_第一批"):
        dirName = os.getcwd() + "\\8月鸿蒙产品_第一批\\" + dir
        configExistFlag = False
        for fileName in os.listdir(dirName):
            if fileName == "config.properties":
                configExistFlag = True
        if not configExistFlag:
            errNameCount += 1
            print(dir)

    print(errNameCount)


def save_config_to_test_properties(appInfo):
    try:
        with(open(os.getcwd() + "\\8月鸿蒙产品_第一批\\" + str(appInfo.order_id) + "\\config.properties", 'w', encoding="utf-8")) as f:
            for key, value in appInfo.__dict__.items():
                if not ["device_name", "certificate_debug_name", "certificate_release_name", "fingerprint1", "fingerprint2", "order_id"].__contains__(key):
                    if key == "orientation" :
                        value = "landscape" if value == "横屏" else "vertical"
                    f.write(f"{key}={value}\n")
    except Exception:
        raise